<?php

namespace mpend\modules\team\models;

use Yii;
use common\models\user\User;
use common\models\workbook\WorkbookMember;
use common\models\workbook\WorkbookInvite;
use common\logics\WorkbookLogic;

/**
 * 班组记工本加入模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class BookMemberForm extends \common\base\FormModel {

    use \common\traits\Constants;

    const TYPE_UNBIND = 'unbind';
    const TYPE_AS_MASTER = 'as_master';
    const TYPE_AS_MANAGER = 'as_manager';
    const TYPE_RELEASE_MASTER = 'release_master';
    const TYPE_RELEASE_MANAGER = 'release_manager';
    const TYPE_DELETE = 'delete';

    /**
     * @var integer
     */
    public $user_id;

    /**
     * @var integer 班组长/工头姓名
     */
    public $type;

    /**
     * @var string 记工薄类型
     */
    protected $modelClass = WorkbookMember::class;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id'], 'integer'],
            [['user_id', 'type'], 'required'],
            [['type'], 'in', 'range' => static::getConstants('type'), 'message' => '{attribute}不在允许范围内'],
            [['type'], 'validateType'],
            [['user_id'], 'validateManager'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'title' => '记工本名称',
            'headman' => '班组长/工头姓名',
            'teamwork' => '是否允许工人记工',
        ];
    }

    public function validateType($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = $this->getModel();
        if (!$model->user_id) {
            return $this->addError($attribute, '记工簿成员暂未绑定微信');
        }
        $type = $this->$attribute;
        if ($type == static::TYPE_RELEASE_MASTER) {
            if ($model->role_id !== WorkbookMember::ROLE_SUPER) {
                return $this->addError($attribute, '当前成员不是班组长，无需进行解除操作');
            }
        } elseif ($type == static::TYPE_RELEASE_MANAGER) {
            if (!$model->role_id) {
                return $this->addError($attribute, '当前成员是普通工人，无需进行取消管理操作');
            }
            if ($model->role_id == WorkbookMember::ROLE_SUPER) {
                return $this->addError($attribute, '请先解除班组长身份后再取消管理员操作');
            }
        } elseif ($type == static::TYPE_AS_MASTER) {
            if (!$model->role_id) {
                return $this->addError($attribute, '需先设置工人为管理员后再设置为班组长');
            }
            if ($model->role_id == WorkbookMember::ROLE_SUPER) {
                return $this->addError($attribute, '当前人员已设置了班组长身份，无需重复操作');
            }
        } elseif ($type == static::TYPE_AS_MANAGER) {
            if ($model->role_id) {
                return $this->addError($attribute, '当前成员已是管理员身份，无需重复操作');
            }
        } elseif ($type == static::TYPE_UNBIND) {
            if ($model->role_id) {
                return $this->addError($attribute, ['管理员身份无法取消绑定微信，如需取消请先取消管理员身份', 42801]);
            }
        }
    }

    public function validateManager($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = $this->getModel();
        $book = $model->workbook;
        if (!$book) {
            return $this->addError($attribute, '记工簿状态已变更，不能进行此操作');
        }
        if (!$book->hasManageControl($this->$attribute)) {
            return $this->addError($attribute, '您没有该记工簿邀请加入的权限');
        }
    }

    public function setExtraAttributes($model) {
        
    }

    public function save() {
        if (!$this->validate()) {
            return $this->dumpError();
        }
        $model = $this->getModel();
        $book = $model->workbook;
        $type = $this->type;
        if ($type == static::TYPE_RELEASE_MASTER) {
            $model->role_id = WorkbookMember::ROLE_ADMIN;
        } elseif ($type == static::TYPE_RELEASE_MANAGER) {
            $model->role_id = WorkbookMember::ROLE_WORKER;
        } elseif ($type == static::TYPE_AS_MASTER) {
            $model->role_id = WorkbookMember::ROLE_SUPER;
            $book->headman = $model->realname;
            $book->headman_mobile = $model->mobile;
        } elseif ($type == static::TYPE_AS_MANAGER) {
            $model->role_id = WorkbookMember::ROLE_ADMIN;
        } elseif ($type == static::TYPE_UNBIND) {
            $model->user_id = 0;
        }
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                return $this->dumpError('成员信息保存失败');
            }
            if (!$book->save()) {
                return $this->dumpError('班组长信息更新失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        return true;
    }

}
